package com.zzyq.pc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
//import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Splitter;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;

public class MongoHelper {
	Logger logger = LoggerFactory.getLogger(MongoHelper.class);
	public static MongoHelper instance = null;
	private Datastore datastore;
	private MongoClient mongoClient;
	private Splitter.MapSplitter mapSplitter = Splitter.onPattern(",|，").omitEmptyStrings().trimResults()
			.withKeyValueSeparator(":");
	private Morphia morphia = new Morphia();

	private MongoHelper() {
		FileInputStream fis = null;
		try {
			// this.morphia.mapPackage("com.zingrow.web.entity");
			fis = new FileInputStream(
					new File(MongoHelper.class.getResource("/").getPath(), "properties/mongo.properties"));

			Properties properties = new Properties();
			properties.load(fis);
			String databaseName = properties.getProperty("mongo_dbName");
			String hostList = properties.getProperty("mongo_host");
			Map<String, String> serverMap = this.mapSplitter.split(hostList);
			List<ServerAddress> serverList = new ArrayList<>();
			if ((null != serverMap) && (!serverMap.isEmpty())) {
				for (Map.Entry<String, String> entry : serverMap.entrySet()) {
					serverList.add(new ServerAddress(entry.getKey(), Integer.parseInt(entry.getValue())));
				}
			}
			if ((serverList.size() > 0) && (StringUtils.isNotBlank(databaseName))) {
				MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
				builder.minConnectionsPerHost(10);
				builder.connectionsPerHost(10);
				builder.connectTimeout(60000);
				builder.socketTimeout(0);
				builder.maxWaitTime(60000);
				builder.threadsAllowedToBlockForConnectionMultiplier(5);
				builder.maxConnectionIdleTime(3600000);
				builder.maxConnectionLifeTime(7200000);
				builder.socketKeepAlive(true);
				this.mongoClient = new MongoClient(serverList, builder.build());
				this.datastore = this.morphia.createDatastore(this.mongoClient, StringUtils.strip(databaseName));
				this.datastore.ensureIndexes();
				this.logger.info("morphia连接池初始化完毕！");
			}
			if (null != fis) {
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
					this.logger.error(e.getMessage());
				}
			}
			return;
		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error(e.getMessage());
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
					this.logger.error(e.getMessage());
				}
			}
		}
	}

	public static MongoHelper getInstance() {
		if (null == instance) {
			instance = new MongoHelper();
		}
		return instance;
	}

	public Datastore getDatastore() {
		return getInstance().datastore;
	}

}
